package pojo;

import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/docar")
public class CarServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        ShopCar myCar = (ShopCar) session.getAttribute("myCar");

        if (myCar == null) {
            myCar = new ShopCar();
            session.setAttribute("myCar", myCar);
        }

        String action = request.getParameter("action");
        if (action == null) {
            action = "";
        }

        if (action.equals("buy")) {
            ArrayList<GoodsSingle> goodslist = (ArrayList<GoodsSingle>) getServletContext().getAttribute("goodslist");
            int id = Integer.parseInt(request.getParameter("id"));
            GoodsSingle single = goodslist.get(id);
            myCar.addItem(single);
            response.sendRedirect("show.jsp");
        } else if (action.equals("remove")) {
            int idt = Integer.parseInt(request.getParameter("id"));
            myCar.removeItem(idt);
            response.sendRedirect("shopcar.jsp");
        } else if (action.equals("clear")) {
            myCar.clearCar();
            response.sendRedirect("shopcar.jsp");
        } else {
            response.sendRedirect("show.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
